package com.xgpro.pc.handleaffairs.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.common.service.BaseService;
import com.xgpro.common.utils.FileTool;
import com.xgpro.common.utils.ReadPropertiesUtil;
import com.xgpro.domain.handleaffairs.dto.HandleAffairsDto;
import com.xgpro.domain.handleaffairs.dto.HandleAffairsUpload;
import com.xgpro.domain.handleaffairs.entity.HandleAffairs;
import com.xgpro.domain.handleaffairs.vo.HandleAffairsVo;
import com.xgpro.domain.studycentre.entity.Plan;
import com.xgpro.mapper.handleaffairs.HandleAffairsMapper;
import com.xgpro.mapper.studycentre.PlanMapper;
import com.xgpro.pc.handleaffairs.service.HandleAffairsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xy
 * @version 1.0
 * @date 2019/10/15 20:33
 */
@Service
@Transactional(readOnly = false)
public class HandleAffairsServiceImpl extends BaseService implements HandleAffairsService {
    /**
     * 未删除状态
     */
    private static final Integer NOREF=0;

    /**
     * 删除状态
     */
    private static final Integer REF=1;

    @Resource
    private HandleAffairsMapper handleAffairsMapper;

    @Value("${DD_ENV.APP_KEY}")
    private String APP_KEY;
    @Value("${DD_ENV.CORP_ID}")
    private String CORP_ID;

    @Value("${DD_ENV.APP_SECRET}")
    private String APP_SECRET;

    @Value("${DD_ENV.AGENTID}")
    private String AGENTID;

    /**
     * 查询列表
     * @param handleAffairsDto
     * @return
     */
    @Override
    public HandleAffairsVo qryHandleAffairsList(HandleAffairsDto handleAffairsDto) {
        Example example = new Example(HandleAffairs.class);
        Example.Criteria criteria = example.createCriteria();
        if(handleAffairsDto.getDeptName()!=null&&!"".equals(handleAffairsDto.getDeptName())){
            criteria.andEqualTo("deptName",handleAffairsDto.getDeptName());
        }
        if(handleAffairsDto.getWorkDescribe()!=null&&!"".equals(handleAffairsDto.getWorkDescribe())){
            criteria.andLike("workDescribe","%"+handleAffairsDto.getWorkDescribe()+"%");
        }
        if(handleAffairsDto.getWorkType()!=null&&!"".equals(handleAffairsDto.getWorkType())){
            criteria.andLike("workType","%"+handleAffairsDto.getWorkType()+"%");
        }
        if(handleAffairsDto.getType()!=null&&!"".equals(handleAffairsDto.getType())){
            criteria.andEqualTo("type",handleAffairsDto.getType());
        }
        example.setOrderByClause("create_time DESC");
        criteria.andEqualTo("ref",NOREF);
        PageHelper.startPage(handleAffairsDto.getPage(),handleAffairsDto.getPageSize());
        Page<HandleAffairs> pages= (Page<HandleAffairs>)handleAffairsMapper.selectByExample(example);
        HandleAffairsVo handleAffairsVo = new HandleAffairsVo();

        List<HandleAffairs> result = pages.getResult();
        if (null != result) {
            for (HandleAffairs plan : result) {
                String filePath = plan.getFilePath().replace(ReadPropertiesUtil.readUrl("nginxUrl"), ReadPropertiesUtil.readUrl("upload_path"));
                File file = new File(filePath);
                String name = file.getName();
                plan.setFileName(name);
                long length = file.length();
                plan.setFileLen(length + "");
                plan.setFilePath(filePath);
                plan.setAgentId(AGENTID);
                plan.setAppKey(APP_KEY);
                plan.setAppSecret(APP_SECRET);
                plan.setCorpId(CORP_ID);
            }
        }
        if(pages!=null){
            handleAffairsVo.setTotals(pages.getTotal());
            handleAffairsVo.setHandleAffairs(pages.getResult());
        }
        return handleAffairsVo;
    }

    /**
     * 根据id删除计划
     * @param id
     * @return
     */
    @Override
    public Integer deleteByHandleAffairsId(Integer id) {
        HandleAffairs handleAffairs = new HandleAffairs();
        handleAffairs.setId(id);
        handleAffairs.setRef(REF);
        return handleAffairsMapper.updateByPrimaryKeySelective(handleAffairs);
    }

    /**
     * 上传文件
     * @param handleAffairsUpload
     * @return
     */
    @Override
    public Integer insertHandleAffairs(HandleAffairsUpload handleAffairsUpload) throws IOException {
        MultipartFile multipartFile = handleAffairsUpload.getMultipartFile();
        if (multipartFile == null){
            throw new BusinessRuntimeException(ResultCodeEnum.FILE_UPLOAD.getCode(),ResultCodeEnum.FILE_UPLOAD.getMessage());
        }
        String planUrl = FileTool.upLoad(multipartFile, ReadPropertiesUtil.readUrl("plan_url"));
        HandleAffairs handleAffairs = new HandleAffairs();
        handleAffairs.setDeptName(handleAffairsUpload.getDeptName());
        handleAffairs.setWorkType(handleAffairsUpload.getWorkType());
        handleAffairs.setFilePath(planUrl);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date=new Date();
        String str=sdf.format(date);
        handleAffairs.setCreateTime(str);
        handleAffairs.setWorkDescribe(handleAffairsUpload.getWorkDescribe());
        handleAffairs.setType(handleAffairsUpload.getType());
        handleAffairs.setRef(NOREF);
        return handleAffairsMapper.insertSelective(handleAffairs);
    }

    /**
     * 下载
     * @param id
     * @return
     */
    @Override
    public ResponseResult downloadHandleAffairs(Integer id) {
        HandleAffairs handleAffairs = handleAffairsMapper.selectByPrimaryKey(id);
        if (handleAffairs.getFilePath().isEmpty()){
            return ResponseResult.failure(ResultCodeEnum.FILE_FAILE_DownLoad.getCode(),ResultCodeEnum.FILE_FAILE_DownLoad.getMessage());
        }
        return ResponseResult.ok(handleAffairs.getFilePath());
    }


}
